package com.inossem.warehousemanage_tv.custom;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Scroller;

import com.inossem.warehousemanage_tv.R;

import java.lang.reflect.Field;
import java.util.List;

/**
 * ViewPager轮播
 *
 * @author 詹建宇
 * @time on 2019/3/5 10:00
 * @email jianyu.zhan@inossem.com
 */
public class RollViewPager extends FrameLayout {

    private Activity mActivity;

    private ViewPager viewPager;
    private LinearLayout llPointGroup;

    private int lastPointPosition = 0;//显示的第几个点

    private int frequency = 2000;//滚动频率

    public RollViewPager(Context context) {
        super(context);
        mActivity = (Activity) context;
        initView();
    }

    public RollViewPager(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mActivity = (Activity) context;
        initView();
    }

    public RollViewPager(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mActivity = (Activity) context;
        initView();
    }

    private void initView() {
        View view = LayoutInflater.from(mActivity).inflate(R.layout.view_roll_viewpager, null, false);
        viewPager = view.findViewById(R.id.viewPager);
        llPointGroup = view.findViewById(R.id.ll_point_group);
        addView(view);
    }

    private Handler handler;

    /**
     * Scroller
     */
    private static class ViewPagerScroller extends Scroller {
        private int mScrollDuration = 1000;//滑动速度

        ViewPagerScroller(Context context) {
            super(context);
        }

        void setScrollDuration(int mScrollDuration) {
            this.mScrollDuration = mScrollDuration;
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, mScrollDuration);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy) {
            super.startScroll(startX, startY, dx, dy, mScrollDuration);
        }

        void initViewPagerScroll(ViewPager viewPager) {
            try {
                Field mScroller = ViewPager.class.getDeclaredField("mScroller");
                mScroller.setAccessible(true);
                mScroller.set(viewPager, this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 适配器
     */
    private static class RollPagerAdapter extends PagerAdapter {

        private List<View> viewList;

        RollPagerAdapter(List<View> viewList) {
            this.viewList = viewList;
        }

        int getViewCount() {
            return viewList.size();
        }

        /**
         * 获得页面的总数
         */
        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        /**
         * 获得相应位置上的view
         * container  view的容器，其实就是viewpager自身
         * position	  相应的位置
         */
        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            container.addView(viewList.get(position % viewList.size()));
            return viewList.get(position % viewList.size());
        }

        /**
         * 判断view和object的对应关系
         */
        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        /**
         * 销毁对应位置上的object
         */
        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }
    }

    //==============================================================================================
    //==========================================public==============================================
    //==============================================================================================

    /**
     * 设置
     *
     * @param list           页面
     * @param isHavePoint    是否显示指示器
     * @param frequency      滚动频率
     * @param scrollDuration 滚动动画时间
     */
    public void setAdapter(List<View> list, boolean isHavePoint, int frequency, int scrollDuration) {
        ViewPagerScroller pagerScroller = new ViewPagerScroller(mActivity);
        pagerScroller.setScrollDuration(scrollDuration);
        pagerScroller.initViewPagerScroll(viewPager);
        this.frequency = frequency;
        final RollPagerAdapter adapter = new RollPagerAdapter(list);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);
        if (isHavePoint) {
            llPointGroup.setVisibility(VISIBLE);
            llPointGroup.removeAllViews();
            for (int i = 0; i < adapter.getViewCount(); i++) {
                ImageView point = new ImageView(mActivity);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(5, 5);
                params.rightMargin = 20;
                point.setLayoutParams(params);
                point.setBackgroundResource(R.drawable.point_bg);
                point.setEnabled(i == 0);
                llPointGroup.addView(point);
            }
            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    position = position % adapter.getViewCount();
                    llPointGroup.getChildAt(position).setEnabled(true);
                    llPointGroup.getChildAt(lastPointPosition).setEnabled(false);
                    lastPointPosition = position;
                }

                @Override
                public void onPageScrolled(int position, float positionOffset, int arg2) {
                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                }
            });
        } else {
            llPointGroup.setVisibility(GONE);
            llPointGroup.removeAllViews();
        }
    }

    /**
     * 设置还是否轮播
     */
    @SuppressLint("HandlerLeak")
    public void setIsRunning(boolean isRunning) {
        if (isRunning) {
            handler = new Handler() {
                public void handleMessage(android.os.Message msg) {
                    if (null == handler || null == viewPager) return;
                    viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
                    handler.sendEmptyMessageDelayed(0, frequency);
                }
            };
            handler.sendEmptyMessageDelayed(0, frequency);
        } else {
            handler = null;
        }
    }

}
